/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author rm61844
 */
public class ClientTCP {
    	private String server;
	private int port;
	private BufferedReader channelRead;
	private PrintWriter channelWriter;
        Socket socket;

	public ClientTCP(String server, int port) {
		this.server = server;
		this.port = port;
	}

	public void execute() {
		createSocket();
		while (socket.isConnected()) {
			String message = makeMessage();
			send(message);
			getResponse();
		}
                System.out.print("Conexao encerrada");
                System.exit(-1);
	}

	public void send(String message) {
            this.channelWriter.println(message);
            this.channelWriter.flush();
	}

	private String makeMessage() {

		String mensagemDigitada = null;

		BufferedReader entradaTeclado = new BufferedReader(
				new InputStreamReader(System.in));
                
		System.out.print("> ");
		try {
			while (!entradaTeclado.ready()) {}
		    mensagemDigitada = entradaTeclado.readLine();
                    
		} catch (IOException e) {
			e.printStackTrace();
		}
                
		return mensagemDigitada;

	}

	private String getResponse() {
		String mensagemRecebida = "";
		try {
                       
                       String line = channelRead.readLine();
                       if(line == null)
                       {
                           System.out.print("Conexao Encerrada");
                           System.exit(-1);
                       }
                       else
                       {
                            while (!line.equals(""))
                            {
                                System.out.println(line);
                                line = channelRead.readLine();
                            }
                       }
		} catch (Exception e) {
                    System.out.print(e.getMessage());
		}
                
		return mensagemRecebida;
	}

	private void createSocket() {
		try {
                        socket = new Socket(this.server, this.port);

			channelRead = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));

			channelWriter = new PrintWriter(socket.getOutputStream());
                        channelWriter.flush();
                        getResponse();
                        
                        
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
